﻿using System;
using System.Configuration;
using System.Data;
using System.Data.Common;
using System.Data.SqlClient;

namespace net.entity.framework.db {
    internal class DataProvider : IDisposable {
        private readonly DbClient client;
        private DbConnection connection;
        private DbCommand command;
        private DbTransaction transaction;
        private DataAdapter dataAdapter;

        internal DataProvider(DbClient client) {
            this.client = client;
        }

        public DbClient Client {
            get { return client; }
        }

        internal DbConnection GetConnection(bool isNew) {
            if (connection == null) {
                if (isNew) {
                    switch (client.Type) {
                        default:
                            connection =
                                new SqlConnection(
                                    ConfigurationManager.ConnectionStrings["MayankConnectionString"].ToString());
                            break;
                    }
                }
            }
            return connection;
        }

        internal IDbCommand GetCommand() {
            if (command == null) {
                switch (client.Type) {
                    default:
                        command = new SqlCommand();
                        break;
                }
            }
            return command;
        }

        internal DataAdapter GetDataAdapter(string commandText) {
            if (dataAdapter == null) {
                switch (client.Type) {
                    default:
                        dataAdapter = new SqlDataAdapter(commandText, (SqlConnection) connection);
                        break;
                }
            }
            return dataAdapter;
        }

        internal DbTransaction GetTransaction(bool isNew) {
            if (transaction == null) {
                if (isNew) {
                    transaction = connection.BeginTransaction();
                }
            }
            return transaction;
        }

        public void Dispose() {
            if (connection.State == ConnectionState.Open) {
                connection.Close();
            }
            connection = null;
            command = null;
            dataAdapter = null;
        }
    }
}